package cn.maxwell.basic.controller;

import cn.maxwell.basic.dto.SmsCodeDto;
import cn.maxwell.basic.service.IVerifyCodeService;
import cn.maxwell.basic.util.BusinessException;
import cn.maxwell.basic.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/verifyCode")
public class VerifyCodeController {

    @Autowired
    private IVerifyCodeService codeService;

    //图形验证码
    @RequestMapping("/image/{key}")
    //从路径中拿到key值
    public JsonResult imageVerifyCode(@PathVariable("key") String key){
        try {
            //返回一个base64编码之后的字符串
            String base64Str = codeService.getImage(key);
            //利用resultObj传递给前端该字符串
            return JsonResult.me().setResultObj(base64Str);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("图形验证码获取失败，请稍后再试");
        }
    }

    /**
     * 获取手机验证码接口
     * @param smsCodeDto
     * @return
     */
    @PostMapping("/smsCode")
    public JsonResult sendSmsCode(@RequestBody SmsCodeDto smsCodeDto){
        try {
            codeService.sendSmsCode(smsCodeDto);
            return new JsonResult();
        } catch (BusinessException e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("发送失败!"+e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("系统异常,请稍后重试!");
        }
    }

    /**
     * 绑定验证码
     *  phone:  111111
     *  imageCode:  adfsa
     *  imageCodeKey: saldfjlsadfjlksd
     */
    @PostMapping("/binderSmsCode")
    public JsonResult binderSmsCode(@RequestBody Map<String,String> map){
        try {
            codeService.binderSmsCode(map);
            return JsonResult.me();
        }catch (BusinessException e) {
            e.printStackTrace();
            return JsonResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("系统异常，稍后重试");
        }
    }
}
